﻿#include "function_detectionGRAY.h"

// Procedures 
void grayDetection(HObject ho_image, HObject *ho_region_show, HTuple hv_row1, HTuple hv_column1,
	HTuple hv_row2, HTuple hv_column2, HTuple hv_low, HTuple hv_high, HTuple *hv_ret,
	HTuple *hv_size)
{

	// Local iconic variables
	HObject  ho_Rectangle, ho_ImageReduced;

	// Local control variables
	HTuple  hv_Channels, hv_Row, hv_Column, hv_message;

	GenRectangle1(&ho_Rectangle, hv_row1, hv_column1, hv_row2, hv_column2);
	ReduceDomain(ho_image, ho_Rectangle, &ho_ImageReduced);
	CountChannels(ho_ImageReduced, &hv_Channels);
	if (0 != (int(hv_Channels == 3)))
	{
		Rgb1ToGray(ho_ImageReduced, &ho_ImageReduced);
	}

	Threshold(ho_ImageReduced, &(*ho_region_show), hv_low, hv_high);

	AreaCenter((*ho_region_show), &(*hv_size), &hv_Row, &hv_Column);
	(*hv_ret) = 1;
	hv_message = "";
	return;
}

DetectionGRAY::DetectionGRAY(QDialog* parent, QSettings* qsettings, QString section) : QDialog(parent)
{
    m_qsettings = qsettings;
    m_section = section;

    //m_model_image_path = QCoreApplication::applicationDirPath() + "/" + m_model_image_path;

    this->setWindowTitle(("产品异常"));
    QRect desktop_rect = QApplication::desktop()->geometry();
    double ratio_x = desktop_rect.width()/1920.0;
    double ratio_y = desktop_rect.height()/1080.0;

    move(0,0);
    setFixedSize(1920*ratio_x,1010*ratio_y);



    m_view = new MyQGraphicsView(this);
    m_view->setGeometry(660 * ratio_x, 0, 1000 * 1.25 * ratio_x, 800 * 1.25 * ratio_y);
    m_view->m_graphics_shape_rect = new GraphicsShapeRect(100,100,100,100);
    m_view->m_scene->addItem(m_view->m_graphics_shape_rect);
    QRectF qrectf = m_view->m_graphics_shape_rect->boundingRect();
    row1 = (int)qrectf.y();
    column1 = (int)qrectf.x();
    row2 = (int)(qrectf.y() + qrectf.height());
    column2 = (int)(qrectf.x() + qrectf.width());
    connect(m_view->m_graphics_shape_rect, &GraphicsShapeRect::sendMessage, m_view->m_pixmapItem, &MyQGraphicsPixmapItem::receiveMessage);

    QSize control_size(120*ratio_x,40*ratio_y);

    QWidget* p = new QWidget(this);
    p->move(0*ratio_x,0*ratio_y);
    p->setFixedSize(600*ratio_x,800*ratio_y);

    QGridLayout *qgridLayout = new QGridLayout();
    p->setLayout(qgridLayout);

    int index = 0;

    QSize ButtonSize(160 * ratio_x, 40 * ratio_y);


//    index++;

    m_qlabel_area_low_threshold = new QLabel();
    m_qlabel_area_low_threshold->setText("面积阈值下限");
    m_qlabel_area_low_threshold->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_area_low_threshold,index,0);
    m_qspinbox_area_low_threshold = new QSpinBox();
    m_qspinbox_area_low_threshold->setFixedSize(control_size);
    m_qspinbox_area_low_threshold->setMinimum(0);
    m_qspinbox_area_low_threshold->setMaximum(10000);
    qgridLayout->addWidget(m_qspinbox_area_low_threshold, index, 1);
    index++;

    m_qlabel_area_up_threshold = new QLabel();
    m_qlabel_area_up_threshold->setText("面积阈值上限");
    m_qlabel_area_up_threshold->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_area_up_threshold,index,0);

    m_qspinbox_area_up_threshold = new QSpinBox();
    m_qspinbox_area_up_threshold->setFixedSize(control_size);
    m_qspinbox_area_up_threshold->setMinimum(1);
    m_qspinbox_area_up_threshold->setMaximum(100000);
    qgridLayout->addWidget(m_qspinbox_area_up_threshold,index,1);


    index++;

    m_qlabel_low = new QLabel();
    m_qlabel_low->setText("灰度阈值最小值");
    m_qlabel_low->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_low,index,0);
    index++;

    m_qspinbox_low = new QSpinBox();
    m_qspinbox_low->setFixedSize(control_size);
    m_qspinbox_low->setMinimum(0);
    m_qspinbox_low->setMaximum(255);
    m_qspinbox_low->setReadOnly(true);
    qgridLayout->addWidget(m_qspinbox_low,index,0);

    m_qslider_low = new QSlider(Qt::Horizontal);
    m_qslider_low->setTickPosition(QSlider::NoTicks);
    m_qslider_low->setSingleStep(1);
    m_qslider_low->setMinimum(0);
    m_qslider_low->setMaximum(255);

    qgridLayout->addWidget(m_qslider_low,index,1);
    index++;

    m_qlabel_high = new QLabel();
    m_qlabel_high->setText("灰度阈值最大值");
    m_qlabel_high->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_high,index,0);
    index++;

    m_qspinbox_high = new QSpinBox();
    m_qspinbox_high->setFixedSize(control_size);
    m_qspinbox_high->setMinimum(0);
    m_qspinbox_high->setMaximum(255);
    m_qspinbox_high->setReadOnly(true);
    qgridLayout->addWidget(m_qspinbox_high,index,0);

    m_qslider_high = new QSlider(Qt::Horizontal);
    m_qslider_high->setTickPosition(QSlider::NoTicks);
    m_qslider_high->setSingleStep(1);
    m_qslider_high->setMinimum(0);
    m_qslider_high->setMaximum(255);

    qgridLayout->addWidget(m_qslider_high,index,1);
    index++;







    m_pushbutton_save_parameter = new QPushButton(this);
    m_pushbutton_save_parameter->setFixedSize(control_size);
    m_pushbutton_save_parameter->setText("保存参数");
    connect(m_pushbutton_save_parameter, &QPushButton::clicked, this, &DetectionGRAY::saveParameter);
    qgridLayout->addWidget(m_pushbutton_save_parameter, index,0);
    index++;

    m_pushbutton_show_orign_image = new QPushButton(this);
    m_pushbutton_show_orign_image->setFixedSize(control_size);
    m_pushbutton_show_orign_image->setText("显示原图");
    connect(m_pushbutton_show_orign_image, &QPushButton::clicked, this,[=]() {
        QImage q_image = matToQImage(m_image);
        m_view->setImage(q_image,"");
        return true;
    });
    qgridLayout->addWidget(m_pushbutton_show_orign_image, index,0);

    m_pushbutton_detection = new QPushButton(this);
    m_pushbutton_detection->setFixedSize(control_size);
    m_pushbutton_detection->setText("检测");
    connect(m_pushbutton_detection, &QPushButton::clicked, this, &DetectionGRAY::detectionImage);
    qgridLayout->addWidget(m_pushbutton_detection, index,1);
    index++;

    m_pushbutton_return = new QPushButton(this);
    m_pushbutton_return->setFixedSize(control_size);
    m_pushbutton_return->setText("退出");
    qgridLayout->addWidget(m_pushbutton_return, index, 0);
    connect(m_pushbutton_return, &QPushButton::clicked, this, [=]() {
        this->hide();
        });

    
    


    loadParameter();
    connect(m_qslider_low, &QSlider::valueChanged, this, [=](int value) {
            m_qspinbox_low->setValue(value);
            saveParameter();
            testImage();
    });
    m_qslider_high->setValue(m_qspinbox_high->value());
    connect(m_qslider_high, &QSlider::valueChanged, this, [=](int value) {
            m_qspinbox_high->setValue(value);
            saveParameter();
            testImage();
    });

    



}

DetectionGRAY::~DetectionGRAY()
{
    ;
}


bool DetectionGRAY::detection( HObject image_in, QString& message)
{
    try
    {
		HTuple htuple_ret, htuple_size;
		grayDetection(image_in, &region_show, row1, column1, row2, column2, m_qspinbox_low->value(), m_qspinbox_high->value(), &htuple_ret, &htuple_size);

        




        



        m_size_error_now  = htuple_size[0].D();

        if(m_size_error_now<=m_area_low_threshold)
        {
            message = "NG缺陷" + QString::number(m_size_error_now) +"面积超出范围";
            return false;
        }

		if (m_size_error_now >= m_area_up_threshold)
		{
			message = "NG缺陷" + QString::number(m_size_error_now) + "面积超出范围";
			return false;
		}

        return true;

    }
	catch (const HalconCpp::HOperatorException& hdev_exception)
	{
		message = hdev_exception.ErrorMessage();
		return false;
	}
	//    message = "HSV OK";
    return true;
}


void DetectionGRAY::detectionImage()
{
    QString message;
	HObject image_in = matToHImage(m_image);
    detection(image_in,message);

    Mat image_show = himageToMat(image_in);
    draw(image_show, image_show);

    QImage q_image = matToQImage(image_show);
    m_view->setImage(q_image, message);
}

void DetectionGRAY::testImage()
{
    QString message;
	HObject image_in = matToHImage(m_image);
    detection(image_in,message);

    Mat image_show = himageToMat(image_in);
    image_show  = Mat::zeros(Size(image_show.cols,image_show.rows),CV_8UC3);
    draw(image_show, image_show);

    QImage q_image = matToQImage(image_show);
    m_view->setImage(q_image, message);
}

void DetectionGRAY::draw(Mat image_in,Mat& image_out)
{
    if(image_in.empty())
        return;
	if (image_in.channels() == 1)
	{
		cvtColor(image_in, image_in, COLOR_GRAY2BGR);
	}
    image_out = drawRegionFill(image_in, region_show, Scalar(0, 0, 255));
    GenEmptyRegion(&region_show);
}

void DetectionGRAY::loadParameter()
{
    row1 = m_qsettings->value(m_section + "/" + "row1",100).toInt();
    column1 = m_qsettings->value(m_section + "/" + "column1",100).toInt();
    row2 = m_qsettings->value(m_section + "/" + "row2",200).toInt();
    column2 = m_qsettings->value(m_section + "/" + "column2",200).toInt();

    m_view->setRectPose(row1, column1, row2, column2);


    m_area_low_threshold = m_qsettings->value(m_section + "/" + "m_area_low_threshold").toInt();
    m_area_up_threshold = m_qsettings->value(m_section + "/" + "m_area_up_threshold").toInt();
    m_low = m_qsettings->value(m_section + "/" + "m_low").toInt();
    m_high = m_qsettings->value(m_section + "/" + "m_high").toInt();
   


    m_qspinbox_area_low_threshold->setValue(m_area_low_threshold);
    m_qspinbox_area_up_threshold->setValue(m_area_up_threshold);


    m_qspinbox_low->setValue(m_low);
    m_qslider_low->setValue(m_low);

    


    m_qspinbox_high->setValue(m_high);
    m_qslider_high->setValue(m_high);




    return ;
}

void DetectionGRAY::saveParameter()
{


    QRectF qrectf = m_view->m_graphics_shape_rect->boundingRect();
    row1 = m_view->m_graphics_shape_rect->pos().y() + (int)qrectf.y();
    column1 = m_view->m_graphics_shape_rect->pos().x() + (int)qrectf.x();
    row2 = m_view->m_graphics_shape_rect->pos().y() + (int)(qrectf.y() + qrectf.height());
    column2 = m_view->m_graphics_shape_rect->pos().x() + (int)(qrectf.x() + qrectf.width());

    m_qsettings->setValue(m_section + "/" + "row1", row1);
    m_qsettings->setValue(m_section + "/" + "column1", column1);
    m_qsettings->setValue(m_section + "/" + "row2", row2);
    m_qsettings->setValue(m_section + "/" + "column2", column2);

    m_area_low_threshold = m_qspinbox_area_low_threshold->value();
	m_area_up_threshold = m_qspinbox_area_up_threshold->value();

    m_low = m_qslider_low->value();
    m_high = m_qslider_high->value();
   


    m_qsettings->setValue(m_section + "/" + "m_area_low_threshold", m_area_low_threshold);
    m_qsettings->setValue(m_section + "/" + "m_area_up_threshold", m_area_up_threshold);

    m_qsettings->setValue(m_section + "/" + "m_low", m_low);
    m_qsettings->setValue(m_section + "/" + "m_high", m_high);



}

bool DetectionGRAY::showDialog()
{
	
    QImage q_image = matToQImage(m_image);
    m_view->setImage(q_image,"");
    return true;
}


